package com.ones.sdp.kit.extra.util;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.*;
import com.ones.sdp.common.core.exception.OnesServiceException;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * http工具类
 * @author Clark
 * @version 2024-08-15
 */
@Slf4j
@UtilityClass
public class HttpKit {
    /**
     * http请求超时时间，默认30秒
     */
    private static final int HTTP_REQUEST_TIMEOUT = 30 * 1000;
    static {
        HttpGlobalConfig.setTimeout(HTTP_REQUEST_TIMEOUT);
    }

    /**
     * get
     * @param urlString
     * @return
     */
    public String get(String urlString) {
        try {
            HttpResponse res = HttpRequest.get(urlString).execute();
            // 判断通讯结果
            if (res.isOk()) {
                return res.body();
            } else {
                // 服务异常
                log.error("-------外部服务异常-------");
                log.error(String.valueOf(res.getStatus()));
                throw new OnesServiceException("外部服务异常");
            }
        } catch (HttpException e) {
            // 服务超时
            log.error("-------外部服务超时-------");
            e.printStackTrace();
            throw new OnesServiceException("外部服务超时");
        } catch (IORuntimeException e) {
            // 服务异常
            log.error("-------外部服务异常-------");
            e.printStackTrace();
            throw new OnesServiceException("外部服务异常");
        }
    }

    /**
     * post
     * @param urlString
     * @param body
     * @return
     */
    public String post(String urlString, String body) {
        HttpRequest req = HttpRequest.post(urlString).body(body);
        return post(req);
    }

    /**
     * post basicAuth
     * @param username
     * @param password
     * @param urlString
     * @param body
     * @return
     */
    public String post4Auth(String username, String password, String urlString, String body) {
        HttpRequest req = HttpRequest.post(urlString).body(body).basicAuth(username, password);
        return post(req);
    }

    /**
     *
     * @param req
     * @return
     */
    private String post(HttpRequest req) {
        try {
            HttpResponse res = req.execute();
            // 判断通讯结果
            if (res.isOk()) {
                return res.body();
            } else {
                // 服务异常
                log.error("-------外部服务异常-------");
                log.error(String.valueOf(res.getStatus()));
                throw new OnesServiceException("外部服务异常");
            }
        } catch (HttpException e) {
            // 服务超时
            log.error("-------外部服务超时-------");
            e.printStackTrace();
            throw new OnesServiceException("外部服务超时");
        } catch (IORuntimeException e) {
            // 服务异常
            log.error("-------外部服务异常-------");
            e.printStackTrace();
            throw new OnesServiceException("外部服务异常");
        }
    }
}